#!/usr/bin/env python3
# coding: utf-8
# Copyright 2024 Huawei Technologies Co., Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
# ===========================================================================
import os
import platform
import glob
import json
from ansible.module_utils import common_utils
from ansible.module_utils.basic import AnsibleModule


class GrafanaUninstaller:

    def __init__(self):
        self.module = AnsibleModule(
            argument_spec=dict(
                tags=dict(type="list", required=True),
            )
        )
        self.run_tags = self.module.params["tags"]
        self.messages = []

    def _module_failed(self):
        return self.module.fail_json(msg="\n".join(self.messages), rc=1, changed=False)

    def _module_success(self):
        return self.module.exit_json(msg="Uninstall grafana success.", rc=0, changed=True)
    
    def stop_service(self):
        self.module.run_command(["systemctl", "stop", "grafana-server"])
       
    
    def uninstall_pkg(self):
        rc, out, err = self.module.run_command("rpm qa |grep grafana", use_unsafe_shell=True)
        for pkg_name in out.split("\n"):
            if "grafana" in pkg_name:
                self.module.run_command(["yum", "remove", "-y", pkg_name])

    def run(self):
        try:
            self.stop_service()
            self.uninstall_pkg()
        except Exception as e:
            self.messages.append(str(e))
            self._module_failed()
        self._module_success()


def main():
    GrafanaUninstaller().run()


if __name__ == "__main__":
    main()